<template>
  <jke-modal
    :visible.sync="jkeForm.visible"
    :width="1200"
    :title="jkeForm.title"
    :fullscreen.sync="jkeForm.fullscreen"
    :switchFullscreen="jkeForm.switchFullscreen"
    @close="jkeModalUpdate"
  >
    <!--  -->
    <crumbs @goBack="goBack" :superiorMenu="['物品管理', '物品']" :currentMenu="jkeForm.title"></crumbs>
    <div class="form-body">
      <a-card title="基本信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="编号" required>
            <a-input
              v-decorator="[
                'goodsCode',
                {
                  rules: [
                    {
                      required: true,
                      message: '请输入物品编号或自动生成',
                    },
                    {
                      message: '该值不可用，系统中已存在！',
                      validator: (rule, value, callback) =>
                        validateDuplicateValue('wms_goods', 'goods_code', value, queryId, callback),
                    },
                  ],
                },
              ]"
              placeholder="不输入则自动生成"
            />
            <span class="btn-text code-btn" @click="genEntityCode">自动生成</span>
          </a-form-item>
          <a-form-item label="名称">
            <a-input
              :maxLength="30"
              v-decorator="['goodsName', { rules: [{ required: true, message: '请输入名称' }] }]"
              placeholder="请输入"
            />
          </a-form-item>
          <a-form-item label="类型">
            <a-select
              v-decorator="['type', { rules: [{ required: true, message: '请选择类型' }] }]"
              placeholder="请选择类型"
              allowClear
              @change="handleSelectType"
            >
              <a-select-option v-for="item in typeList" :key="item.value" :value="item.value">
                {{ item.title }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="分类">
            <a-tree-select
              v-decorator="['category', { rules: [{ required: true, message: '请选择类型' }] }]"
              allow-clear
              v-model="value"
              :multiple="false"
              placeholder="请选择"
              style="width: 100%"
              :tree-data="treeData"
              :replaceFields="replaceFields"
              :show-checked-strategy="SHOW_PARENT"
              search-placeholder="请选择"
            />
          </a-form-item>
          <a-form-item label="规格">
            <a-input v-decorator="['spec']" placeholder="请输入规格" />
          </a-form-item>

          <a-form-item label="基本单位/生产单位">
            <a-select
              v-decorator="['basicUnit', { rules: [{ required: true, message: '请选择' }] }]"
              allowClear
              placeholder="请选择"
              @change="basicUnitChange"
            >
              <a-select-option :value="undefined">请选择</a-select-option>
              <a-select-option v-for="(item, key) in dictOptionsGoodsUnit" :key="key" :value="item.value">
                <span style="display: inline-block; width: 100%" :title="item.text || item.label">
                  {{ item.text || item.label }}
                </span>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
        <a-form layout="vertical">
          <a-form-item label="附件" style="flex: 1">
            <file-upload :ids="attachment" fileType="image" @getFileList="getFileList"></file-upload>
            <p style="line-height: 30px;color:#8d8d8d;">最多上传5个文件，每个大小不可超过20M</p>
          </a-form-item>
        </a-form>
      </a-card>
      <a-card title="辅助单位" :bordered="false" style="margin-top: 12px">
        <a-col :span="24" style="margin-bottom: 38px">
          <j-editable-table
            :ref="refKeys[0]"
            :loading="goodsUnitTable.loading"
            :columns="goodsUnitTable.columns"
            :dataSource="goodsUnitTable.dataSource"
            :maxHeight="300"
            :disabled="formDisabled"
            :rowNumber="true"
            :rowSelection="true"
            :actionButton="true"
            :delActionBtn="false"
            @valueChange="assistUnitChange"
          >
            <template v-slot:isUse="props">
              <a-switch :checked="props.value == '0'" @change="(bl, e) => onChangeSwitch(bl, props)" />
            </template>
          </j-editable-table>
        </a-col>
      </a-card>
      <a-card title="采购" :bordered="false" style="margin: 12px 0">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="预留采购时长（天）" style="flex: 1">
            <a-input
              v-decorator="[
                'estimatePurchaseTime',
                {
                  rules: [{ pattern: /^[1-9]\d*$/, message: '请输入零以上的正整数' }],
                },
              ]"
              placeholder="请输入"
            />
            <!-- <a-textarea placeholder="请输入" auto-size v-decorator="['estimatePurchaseTime']" /> -->
          </a-form-item>
        </a-form>
        <!-- <a-col :span="24" style="margin-bottom: 38px">
          <j-editable-table
            :ref="refKeys[1]"
            :loading="supplier.loading"
            :columns="supplier.columns"
            :dataSource="supplier.dataSource"
            :maxHeight="300"
            :disabled="formDisabled"
            :rowNumber="true"
            :rowSelection="true"
            :actionButton="true"
          >
            <template v-slot:supplierId="props">
              <a-select
                @popupScroll="popupScroll"
                style="width: 100%"
                :not-found-content="supplierDropList.length > 0 ? null : '暂无数据'"
                :defaultValue="props.value"
                @select="(bl, e) => onChangeSelect(bl, props)"
              >
                <a-select-option v-for="(item, key) in supplierDropList" :key="key" :value="item.id">
                  <span style="display: inline-block; width: 100%" :title="item.fullName">
                    {{ item.fullName }}
                  </span>
                </a-select-option>
              </a-select>
            </template>
            <template v-slot:action="props">
              <a-popconfirm
                title="是否删除?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDeleteS(props)"
                @cancel="cancelS"
              >
                <a style="padding-left: 3px">删除</a>
              </a-popconfirm>
            </template>
          </j-editable-table>
        </a-col> -->
      </a-card>
      <div>
        <Examine
          @submitProcess="submitProcess"
          :type="jkeForm.title === '新建物品' ? '0' : '1'"
          id="WMS_GOODS"
          ref="examine"
        />
        <div style="height: 50px"></div>
      </div>
    </div>
    <!-- <div style="height:75px"></div> -->
    <div class="form-footer footer-submit">
      <!-- <div class="foot"> -->
      <a-button @click="goBack" class="submitBtn" style="margin-right: 10px"> 取消 </a-button>
      <a-button type="primary" class="submitBtn" :loading="loadingSubmit" @click="submitProcess"> 提交 </a-button>
    </div>

    <!-- </div> -->
  </jke-modal>
</template>
<script>
import {
  VALIDATE_NO_PASSED,
  FormTypes,
  getRefPromise,
  validateFormAndTables,
  validateTables,
} from '@/utils/JEditableTableUtil'
import crumbs from '@/components/crumbs.vue'
import { API } from '@/api/requestFzs'
import { validateDuplicateValue } from '@/utils/util'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import Examine from '@/components/examine'
import {
  goodsAdd,
  goodsEdit,
  getDictModel,
  categoryGetTree,
  goodsQueryById,
  getSupplierPageList,
} from '@/api/goodsManagement'
import { TreeSelect } from 'ant-design-vue'
const SHOW_PARENT = TreeSelect.SHOW_PARENT
const treeData = []
export default {
  data() {
    return {
      jkeForm: {
        title: '',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      type: '0', //0是新增，1是编辑，2是详情
      id: 'WMS_GOODS', //此id用获取流程审批节点和获取详情中流程流转记录（注意：两者id并不相同）
      typeList: [], //类型
      queryId: '',
      validateDuplicateValue, //自动生成编码
      loadingSubmit: false, //防止多次提交
      supplierParam: {
        pageNo: 1,
        pageSize: 10,
      },
      submitApi: goodsAdd,
      isEdit: false,
      replaceFields: {
        children: 'children',
        title: 'name',
        key: 'id',
        value: 'id',
      },
      dictOptionsGoodsUnit: '', //基本单位下拉
      tableUnit: '', //表格里基本单位下拉
      // tableUnitChange: '', //转换率
      switchChecked: true, //辅助单位-表格-是否启用
      supplierDropList: [], //供应商下拉
      value: '',
      treeData,
      SHOW_PARENT,
      // 辅助单位
      refKeys: ['goodsUnitTable', 'supplier'],
      tableKeys: ['goodsUnitTable', 'supplier'],
      goodsUnitTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '辅助单位',
            key: 'assistUnit',
            type: FormTypes.select,
            options: this.dictOptionsGoodsUnit,
            placeholder: '请选择',
            width: '40%',
            defaultValue: '',
            isrequired: true,
            validateRules: [
              {
                required: true, // 必填
                message: '${title}不能为空', // 提示的文本
              },
              {
                unique: true, // 唯一
                message: '${title}不能重复', // 提示的文本
              },
            ],
          },
          {
            title: '一辅助单位等于多少基本单位',
            key: 'conversionRate',
            type: FormTypes.input,
            // options: this.tableUnitChange,
            placeholder: '请输入',
            width: '40%',
            defaultValue: '',
            isrequired: true,
            validateRules: [
              {
                required: true, // 必填
                message: '${title}不能为空', // 提示的文本
              },
              { pattern: /^(([0-9]+)|([0-9]+\.[0-9]{0,4}))$/, message: '请输入零以上的数字（最多保留4位小数）' },
            ],
          },
          {
            title: '是否启用',
            key: 'isUse',
            type: FormTypes.slot, // 定义该列为 自定义插值列
            slotName: 'isUse', // slot 的名称，对应 v-slot 冒号后面和等号前面的内容
            defaultValue: '0',
          },

          // {
          //   title: '操作',
          //   width: '20%',
          //   key: 'action',
          //   type: FormTypes.slot,
          //   placeholder: '选择${title}',
          //   slotName: 'action',
          //   defaultValue: '',
          // },
        ],
      },
      supplier: {
        loading: false,
        dataSource: [],
        columns: [
          // {
          //   title: '供应商名称',
          //   key: 'supplierName',
          //   type: FormTypes.select,
          //   options: this.projectList,
          //   placeholder: '请选择',
          //   width: '40%',
          //   defaultValue: '',
          //   validateRules: [
          //     {
          //       required: true, // 必填
          //       message: '${title}不能为空', // 提示的文本
          //     },
          //   ],
          // },
          {
            title: '供应商名称',
            key: 'supplierId',
            type: FormTypes.slot,
            slotName: 'supplierId',
            width: '40%',
          },
          {
            title: '操作',
            width: '20%',
            key: 'action',
            type: FormTypes.slot,
            placeholder: '选择${title}',
            slotName: 'action',
            defaultValue: '',
          },
        ],
      },
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      attachment: '',
    }
  },
  components: {
    FileUpload,
    crumbs,
    Examine,
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    mainDivWidth() {
      let mainDiv = document.querySelector('.ant-layout-content') //ant-layout-content
      return `${mainDiv.clientWidth}px`
    },
  },
  methods: {
    jkeModalUpdate() {
      if (this.$route.path == '/dashboard/analysis') {
        this.$store.commit('SET_CURRENT_PREFIX','/jksaas-mgt/mgt')
      }
    },
    initForm(id) {
      Object.assign(this.$data, this.$options.data.call(this));
      this.$store.commit('SET_CURRENT_PREFIX','/jksaas-produce/produce')
      this.getDictModel()
      this.getDetail(id)
      this.getSupplier()
    },
    /* 选择基本单位时，基本单位不能与辅助单位重复 */
    basicUnitChange(v) {
      const { values } = this.$refs.goodsUnitTable.getValuesSync({ validate: false })
      if (!v || values.length == 0) {
        return
      }
      for (let i = 0; i < values.length; i++) {
        const unit = values[i]
        if (v == unit.assistUnit) {
          this.$nextTick(() => {
            this.form.setFieldsValue({
              basicUnit: undefined,
            })
          })
          this.$antdMessage.warning('基本单位不能与辅助单位重复!')
          return
        }
      }
    },
    /* 选择辅助单位时，辅助单位不能与基本单位重复 */
    assistUnitChange(type, row, column, value, target) {
      this.form.validateFields(['basicUnit'], (errors, values) => {
        console.log(type, '-', values)
        if (type.column.key != 'assistUnit') {
          return
        }
        if (!values.basicUnit || type.column.key != 'assistUnit') {
          return
        } else {
          if (type.value == values.basicUnit) {
            this.$antdMessage.warning('辅助单位不能与基本单位重复!')
            this.$refs.goodsUnitTable.setValues([
              {
                rowKey: type.row.id, // 行的id
                values: {
                  assistUnit: '',
                },
              },
            ])
          }
        }
      })
    },
    /* 自动生成 */
    genEntityCode() {
      API.genEntityCode({ entityCode: 'WMS_GOODS' }).then((res) => {
        if (res.code == 200) {
          this.form.setFieldsValue({
            goodsCode: res.result,
          })
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    /* 获取编辑详情 */
    getDetail(id) {
      this.jkeForm.visible = true
      this.queryId = id
      if (id) {
        this.jkeForm.title = '编辑物品'
        this.submitApi = goodsEdit
        this.isEdit = true
        goodsQueryById({ id: id }).then((res) => {
          if (res.code == 200) {
            this.form.setFieldsValue(res.result)
            this.attachment = res.result.attachment
            this.goodsUnitTable.dataSource = res.result.goodsAssistUnitList
            res.result.supplierList.forEach((sup) => {
              sup.supplierId = sup.id
            })
            this.supplier.dataSource = res.result.supplierList
          }
        })
      } else {
        this.jkeForm.title = '新建物品'
      }
    },
    // 供应商 change
    onChangeSelect(bl, props) {
      this.$refs.supplier.setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            supplierId: bl,
          },
        },
      ])
      const { error, values } = this.$refs.supplier.getValuesSync({ validate: true })
      let idLength = 0
      values.forEach((item) => {
        if (item.supplierId == bl) {
          idLength++
        }
      })
      if (idLength == 2) {
        this.$antdMessage.error('该供应商已存在')
        this.$refs.supplier.removeRows(props.rowId)
        this.$refs.supplier.setValues([
          {
            rowKey: props.rowId, // 行的id
            values: {
              // 在这里 values 中的 specifications 是你 columns 中配置的 key
              supplierId: '',
            },
          },
        ])
      }
    },
    onChangeSwitch(bl, props) {
      console.log(props, bl, 'e')
      if (bl) {
        this.$refs.goodsUnitTable.setValues([
          {
            rowKey: props.rowId, // 行的id
            values: {
              isUse: '0',
            },
          },
        ])
      } else {
        this.$refs.goodsUnitTable.setValues([
          {
            rowKey: props.rowId, // 行的id
            values: {
              isUse: '1',
            },
          },
        ])
      }
    },
    getDictModel() {
      // 字典接口

      // 类型字典
      let parametersType = { dictCode: 'wms_goods_type' }
      getDictModel(parametersType).then((res) => {
        if (res.code == 200) {
          this.typeList = res.result
          console.log(res, 'inStockStatus')
        }
      })
      // 基本单位
      getDictModel({ dictCode: 'wms_goods_unit' }).then((res) => {
        // 表单
        this.dictOptionsGoodsUnit = res.result
        this.goodsUnitTable.columns[0].options = this.dictOptionsGoodsUnit
      })
      // // 单位换算
      // getDictModel({ dictCode: 'mess_conversion_rate' }).then((res) => {
      //   // 表格
      //   this.goodsUnitTable.columns[1].options = res.result
      // })
      // 类型字典
      let parameters = { dictCode: 'inStockStatus' }
      getDictModel(parameters).then((res) => {
        if (res.code == 200) {
          console.log(res, 'inStockStatus')
        }
      })
      // 取分类树
      categoryGetTree({ code: 'B05' }).then((res) => {
        let arr = res.result
        arr.map((item) => {
          if (item.children.length > 0) {
            item.disabled = true
            ;(function bianli(e = item) {
              e.children.forEach((item) => {
                if (item.children.length > 0) {
                  item.disabled = true
                  bianli(item)
                }
              })
            })()
          }
        })
        this.treeData = arr
      })
    },
    getSupplier() {
      getSupplierPageList(this.supplierParam).then((res) => {
        res.result.forEach((item) => {
          this.supplierDropList.push(item)
        })
      })
      console.log(this.supplierDropList, 'this.supplierDropList')
    },
    popupScroll(e) {
      const { scrollHeight, scrollTop, clientHeight } = e.target
      if (scrollHeight - scrollTop - clientHeight < 1) {
        this.supplierParam.pageNo++
        this.supplierParam.pageSize = parseInt(this.supplierParam.pageSize) + 10
        this.getSupplier()
      }
    },
    // 类型下拉选择
    handleSelectType(value) {
      console.log(value)
      // this.form.setFieldsValue({
      //   note: `Hi, ${value === 'male' ? 'man' : 'lady'}!`,
      // })
    },
    /* 面包屑返回 */
    goBack() {
      this.jkeModalUpdate()
      this.jkeForm.visible = false
    },
    /* 获取附件 */
    getFileList(v) {
      this.attachment = v
      console.log('上传的附件id：', v)
    },
    // 提交（必须使用名为submitProcess方法进行提交）
    submitProcess(e) {
      if (e.nodeDtos) {
        this.processDataVo = e
        console.log(e, this.processDataVo, 'processDataVo')
        // 获取到数据后写表单提交的方法
        this.saveForm()
      } else {
        // 调用子组件的方法获取数据
        this.$refs.examine.confirm()
      }
    },
    saveForm() {
      // 获取到数据后写表单提交的方法
      const { error, values } = this.$refs.goodsUnitTable.getValuesSync({ validate: true })
      console.log(values, 'values save')
      if (!error) {
        values.forEach((item) => {
          delete item.id
          if (item.isUse == '') {
            item.isUse = '0'
          }
        })
        let pValue = values
        console.log(pValue, 'pValue')
        this.handleSubmit(pValue)
      }
    },
    handleTo(pValue) {
      const { error, values } = this.$refs.supplier.getValuesSync({ validate: true })
      let sValue = ''
      values.forEach((item) => {
        delete item.id
        delete item.action
        sValue += item.supplierId + ','
      })
      if (sValue.length > 0) {
        sValue = sValue.substr(0, sValue.length - 1)
      }

      this.handleSubmit(pValue, sValue)
    },
    handleSubmit(pValue) {
      console.log(pValue, 'pValue, sValue')
      this.form.validateFields((err, values) => {
        if (!err) {
          let parameters = {
            ...values,
            attachment: this.attachment,
            goodsAssistUnitList: pValue,
            processDataVo: this.processDataVo,
          }
          if (this.isEdit) {
            parameters.id = this.queryId
          }
          this.loadingSubmit = true
          this.submitApi(parameters).then((res) => {
            if (res.code == 200) {
              this.loadingSubmit = false
              let subMsg = this.isEdit ? '物品编辑成功！' : '物品创建成功！'
              this.$antdMessage.success(subMsg)
              this.$emit('refresh')
              this.goBack()
            } else {
              this.loadingSubmit = false
              this.$antdMessage.error(res.message)
            }
          })
        }
      })
    },
    // 辅助单位-删除
    handleDelete(props) {
      let { rowId, target } = props
      target.removeRows(rowId)
    },
    cancel() {},
    // 采购-删除
    handleDeleteS(props) {
      let { rowId, target } = props
      target.removeRows(rowId)
    },
    cancelS() {},
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
/deep/.ant-form-vertical {
  display: flex;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 120px);
  overflow-y: scroll;
}
.submitBtn {
  .flex(flex-end, center);
  padding: 8px;
}
.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
// .foot{
//   float: right;
//   display: flex;
//   padding: 15px;
// }
</style>
